package org.mspring.mlog.web.module.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Post;
import org.mspring.mlog.entity.Tag;
import org.mspring.mlog.entity.constants.PageNames;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.service.TagService;
import org.mspring.platform.dao.Page;
import org.mspring.platform.web.freemarker.FreemarkerVariableNames;
import org.mspring.platform.web.freemarker.widget.stereotype.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author Gao Youbo
 * @since 2013-3-4
 */
@Action
@RequestMapping("/post")
public class Web_ArchiveTagWidget extends Web_AbstractWidget {
    @Autowired
    private PostService postService;
    @Autowired
    private TagService tagService;

    @RequestMapping("/tag")
    public String archiveByTag(@RequestParam(defaultValue = "0") long tag, @RequestParam(defaultValue = "1") int page, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        if (tag < 1) {
            response.sendError(404);
            return null;
        }
        Page<Post> postPage = new Page<>();
        postPage.setPageNo(page);
        postService.listByTag(postPage, tag);

        // 这个tagId是判断是否是tag归档的依据
        model.addAttribute("tagId", tag);
        model.addAttribute(FreemarkerVariableNames.POST_PAGE, postPage);

        // 设置当前页
        Tag t = tagService.get(tag);
        model.addAttribute(FreemarkerVariableNames.TAG_ARCHIVE_NAME, t.getName());
        setCurrnetPage(model, PageNames.TAG_ARCHIVE);
        return "skin:/archiveTag";
    }

}
